#include "temperature.h"
#include <FreeRTOS.h>
#include <task.h>
#include "driver_dht11_basic.h"
#include "led_op.h"

static float temperature;
static uint8_t humidity;

static void update_temperature(void *pvParameters)
{
    int ret, retry, error_count = 0;

    dht11_basic_init();
    while (error_count < 3) {
        retry = 0;
        do {
            retry++;
            ret = dht11_basic_read(&temperature, &humidity);
            if (ret != 0) {
                vTaskDelay(333);
            }
        } while (ret != 0 && retry < 10);
        
        if (ret == 0) {
            led_clear_status(LED_STAT_SENSOR_FAULT);
            error_count = 0;
        } else {
            led_set_status(LED_STAT_SENSOR_FAULT);
            error_count++;
        }

        vTaskDelay(14000);
    }

    led_clear_status(LED_STAT_SENSOR_FAULT);
    vTaskDelete(NULL);
}

void init_temperature(void)
{
    xTaskCreate(update_temperature, (char *)"update temperature", 1024, NULL, 29, NULL);
}

float get_temperature(void)
{
    return temperature;
}

uint8_t get_humidity(void)
{
    return humidity;
}

